package org.yuanqiframework.yuanqi.boot.sys.service.impl;

import cn.hutool.core.codec.Base64Decoder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.yuanqiframework.yuanqi.core.utils.StringUtils;
import org.yuanqiframework.yuanqi.boot.sys.dto.SysUrlWhitelistDTO;
import org.yuanqiframework.yuanqi.boot.sys.entity.SysUrlWhitelist;
import org.yuanqiframework.yuanqi.boot.sys.mapper.SysUrlWhitelistMapper;
import org.yuanqiframework.yuanqi.boot.sys.service.SysUrlWhitelistService;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cbt28
 * @description 针对表【sys_url_whitelist】的数据库操作Service实现
 * @createDate 2025-08-20 23:08:07
 */
@Service
public class SysUrlWhitelistServiceImpl extends ServiceImpl<SysUrlWhitelistMapper, SysUrlWhitelist>
        implements SysUrlWhitelistService {
    @Resource
    private SysUrlWhitelistMapper sysUrlWhitelistMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(List<SysUrlWhitelistDTO> sysUrlWhitelistDT) {

        List<SysUrlWhitelist> list = new LinkedList<>();
        sysUrlWhitelistDT.forEach(sysUrlWhitelistDTO -> {
            String urlId = sysUrlWhitelistDTO.getUrlId();
            String methodUrl = new String(Base64Decoder.decode(urlId.getBytes()));
            String[] arr = methodUrl.split("<=>");
            String allowAnonymous = sysUrlWhitelistDTO.getAllowAnonymous();
            SysUrlWhitelist sysUrlWhitelist = new SysUrlWhitelist();
            sysUrlWhitelist.setId(StringUtils.getUUID());
            sysUrlWhitelist.setUrlId(urlId);
            sysUrlWhitelist.setHttpMethod(arr[0]);
            sysUrlWhitelist.setHttpUrl(arr[1]);
            sysUrlWhitelist.setAllowAnonymous(allowAnonymous);
            list.add(sysUrlWhitelist);
        });
        List<String> urlIds = list.stream().map(SysUrlWhitelist::getUrlId).collect(Collectors.toList());
        if (!urlIds.isEmpty()) {
            sysUrlWhitelistMapper.delete(new LambdaQueryWrapper<SysUrlWhitelist>()
                    .in(SysUrlWhitelist::getUrlId, urlIds));
        }
        List<BatchResult> batchResults = sysUrlWhitelistMapper.insertOrUpdate(list);
        return batchResults != null && !batchResults.isEmpty();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(List<String> ids) {
        return sysUrlWhitelistMapper.deleteByIds(ids) > 0;
    }
}




